package com.hb.game.pk.ui;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.allenliu.versionchecklib.core.http.HttpHeaders;
import com.allenliu.versionchecklib.core.http.HttpParams;
import com.allenliu.versionchecklib.core.http.HttpRequestMethod;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.RequestVersionListener;
import com.google.gson.Gson;
import com.hb.game.pk.APP;
import com.hb.game.pk.R;
import com.hb.game.pk.adpter.MainFragmentListAdapter;
import com.hb.game.pk.api.Host;
import com.hb.game.pk.base.BaseActivity;
import com.hb.game.pk.beans.Update;
import com.hb.game.pk.event.ClickTransEvent;
import com.hb.game.pk.event.DownLoadEvent;
import com.hb.game.pk.ui.fragment.ContactFragment;
import com.hb.game.pk.ui.fragment.GameFragment;
import com.hb.game.pk.ui.fragment.MainFragment;
import com.hb.game.pk.ui.fragment.MineFragment;
import com.hb.game.pk.utils.AppUtils;
import com.hb.game.pk.utils.OpenMethod;
import com.hb.game.pk.utils.StringUtils;
import com.hb.game.pk.utils.ToastUtils;
import com.hb.game.pk.utils.file.FilePathManager;
import com.hb.game.pk.widgets.BaseViewPager;
import com.hb.game.pk.widgets.bottombar.AlphaTabsIndicator;
import com.hb.game.pk.widgets.bottombar.OnTabChangedListner;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.BindView;

public class MainActivity extends BaseActivity<Update> {

    private File saveFile;
    ExecutorService downLoadPool = Executors.newFixedThreadPool(1);
    private Update.DataBean data;
    private MaterialDialog mDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected int getRootViewId() {
        return R.id.layout_root;
    }

    @Override
    protected int getRefreshId() {
        return 0;
    }

    @Override
    protected int getListViewId() {
        return 0;
    }

    @BindView(R.id.vp_content)
    BaseViewPager mContent;
    @BindView(R.id.al_bottom)
    AlphaTabsIndicator mMenuBottomBox;
    @BindView(R.id.rl_dialog)
    RelativeLayout rlDialog;
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.tv_cansle)
    TextView tvCansle;
    @BindView(R.id.tv_ok)
    TextView tvOk;
    private ArrayList<Fragment> mFragmentList;
    String detail;
    String url;

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onRefreshData() {
        super.onRefreshData();
        newUpdate();
//        call = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).update(AppUtils.getAppVersionName(this));
//        call.enqueue(new Callback<Update>() {
//            @Override
//            public void onResponse(Call<Update> call, Response<Update> response) {
//                Update body = response.body();
//                if (body == null) {
//                    ToastUtils.showToast("请求错误");
//                    tvUpdate.setText("请求错误");
//                    return;
//                }
//                if (body.getStatus() != 1) {
//                    ToastUtils.showToast(body.getInfo());
//                    tvUpdate.setText(body.getInfo());
//                    return;
//                }
//                data = body.getData();
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
//                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 11);
//                } else {
//                    doUpdate();
//                }
//            }
//
//            @Override
//            public void onFailure(Call<Update> call, Throwable t) {
//                rlDialog.setVisibility(View.GONE);
//                ToastUtils.showToast("获取更新失败");
//            }
//        });
    }

    private void newUpdate() {
        HttpHeaders httpHeader = new HttpHeaders();
        httpHeader.put("token", APP.Token);
        httpHeader.put("userid", APP.uid);
        HttpParams httpParam = new HttpParams();
        httpParam.put("currentversion", AppUtils.getAppVersionName(this));
        DownloadBuilder update = AllenVersionChecker
                .getInstance()
                .requestVersion()
                .setHttpHeaders(httpHeader)
                .setRequestMethod(HttpRequestMethod.POST)
                .setRequestParams(httpParam)
                .setRequestUrl(Host.HOST + "app/index/update")
                .request(new RequestVersionListener() {
                    @Nullable
                    @Override
                    public UIData onRequestVersionSuccess(String result) {
                        //拿到服务器返回的数据，解析，拿到downloadUrl和一些其他的UI数据
                        Update update = new Gson().fromJson(result, Update.class);
                        if (update == null) {
                            ToastUtils.showToast("请求错误");
                            return null;
                        }
                        if (update.getStatus() != 1) {
                            ToastUtils.showToast(update.getInfo());
                            return null;
                        }
                        UIData uiData = UIData
                                .create()
                                .setDownloadUrl(update.getData().getUrl())
                                .setTitle("更新提示")
                                .setContent(update.getData().getDetail());
                        //放一些其他的UI参数，拿到后面自定义界面使用
//                        uiData.getVersionBundle().putString("key", "your value");
                        return uiData;

                    }

                    @Override
                    public void onRequestVersionFailure(String message) {

                    }
                });
//        update.setForceUpdateListener(new ForceUpdateListener() {
//
//            @Override
//            public void onShouldForceUpdate() {
//                ToastUtils.showToast("正在下载更新，请稍后");
//            }
//        });
        update.executeMission(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 11) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] ==
                    PackageManager.PERMISSION_GRANTED) {
                doUpdate();
            }
        }
    }

    private void doUpdate() {
        rlDialog.setVisibility(View.VISIBLE);
        detail = data.getDetail();
        url = data.getUrl();
        tvUpdate.setText(detail);
        saveFile = new File(FilePathManager.getUpdatePath(), getResources().getString(R.string.app_name_py) + ".apk");
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtils.isEmpty(url)) {
                    rlDialog.setVisibility(View.GONE);
                } else {
                    tvOk.setEnabled(false);
                    OpenMethod.startDownLoad(MainActivity.this, url, saveFile, downLoadPool);
                }
            }
        });
        tvOk.setVisibility(View.VISIBLE);
    }

    @Subscribe
    public void onEvent(DownLoadEvent e) {
        downLoadPool.shutdown();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                rlDialog.setVisibility(View.GONE);
            }
        });
        OpenMethod.install(this, saveFile);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mFragmentList = new ArrayList<Fragment>();
        FragmentManager fm = getSupportFragmentManager();
        mFragmentList.add(new MainFragment());
        mFragmentList.add(new ContactFragment());
        mFragmentList.add(new GameFragment());
        mFragmentList.add(new MineFragment());
        mContent.setAdapter(new MainFragmentListAdapter(fm, mFragmentList));
        mContent.setOnPageChangeListener(pageChangeListener);
        mMenuBottomBox.setViewPager(mContent);                     //设置ViewPager
        mContent.setOffscreenPageLimit(4);
        mContent.setNoScroll(true);
        mMenuBottomBox.setOnTabChangedListner(tabChangedListner);   //设置底部tab点击监听
        mContent.setCurrentItem(2);

        List<Integer> resource = new ArrayList<>();
        resource.add(R.mipmap.iv_1);
        resource.add(R.mipmap.iv_2);
        resource.add(R.mipmap.iv_3);
        resource.add(R.mipmap.iv_4);
        resource.add(R.mipmap.iv_5);
        resource.add(R.mipmap.iv_6);
        resource.add(R.mipmap.iv_7);
        resource.add(R.mipmap.iv_8);
        resource.add(R.mipmap.iv_9);
        resource.add(R.mipmap.iv_10);
        resource.add(R.mipmap.iv_11);
        resource.add(R.mipmap.iv_12);
        resource.add(R.mipmap.iv_13);
        resource.add(R.mipmap.iv_14);
        resource.add(R.mipmap.iv_15);
        resource.add(R.mipmap.iv_16);
        resource.add(R.mipmap.iv_17);
        resource.add(R.mipmap.iv_18);
        resource.add(R.mipmap.iv_19);
        resource.add(R.mipmap.iv_20);
        resource.add(R.mipmap.iv_21);
        resource.add(R.mipmap.iv_22);
        resource.add(R.mipmap.iv_23);
        resource.add(R.mipmap.iv_24);

        APP.headResource = resource;
        rlDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            mMenuBottomBox.setTabCurrenItem(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    OnTabChangedListner tabChangedListner = new OnTabChangedListner() {
        @Override
        public void onTabSelected(int tabNum) {
            mContent.setCurrentItem(tabNum);
        }
    };

    @Subscribe
    public void onEvent(ClickTransEvent e) {
        mMenuBottomBox.setTabCurrenItem(1);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        AllenVersionChecker.getInstance().cancelAllMission(this);
    }
}
